#/bin/bash 
#description: Add keepalived instance configuration
#author	weskiller
#date 2017-02-19
#regexp
IPGEXP="((25[0-3]|2[0-4][0-9]|1[0-9][0-9]|[0-9]?[1-9])\.)((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.){2}(25[0-4]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])"
#game port count
count=5
#game-id
id="$1"
#game sever ip address
address="$2"
#game server port
port="$3"
#basdir
basedir=`dirname $0`

#get resource from curl
url="http://zabbix.8z.net/proxy/gresource"
tmp=`mktemp /tmp/resource.XXX`
curl "$url" > $tmp 2>/dev/null
if head -1 $tmp|grep -Pq "^#20\d\d-\d\d-\d\d";then
        . $tmp
else
        echo "resource not found."
        rm -f $tmp
        exit 1
fi
rm -f $tmp

#example instance configuration file
example=$basedir/instance_example
#game list file
gamelist=$basedir/gamelist
#check gamelist scripts
check=$basedir/check_gamelist.sh
#config directory
dirconf=/etc/keepalived/instance
#check address
check_address () {
if ! echo $address|grep -Pq "^$IPGEXP$";then
        echo "game server ip address is error!"
        exit 1
fi
}

#check port
check_port () {
if ! [ ${port:-0} -ge 7000 -a ${port:-0} -le 9000 ];then
        echo "game server port is not between 7000 and 9000 !";
        exit 1
fi
}

#check id
check_id () {
if [ "x$id" == "x" ];then
	echo "game-id is empty!"
	exit 1
elif [ "x$id" == "xall" ];then
	/bin/bash $check
	result=$?
	if [ $result -gt 0 ];then
		echo "exit..."
		exit $result
	fi
	declare -i index=0
	while read line;do
		if echo $line|grep -Pq "(?<=#server )$IPGEXP";then
			rserver=`echo $line|grep -Po "(?<=#server )$IPGEXP"`
		elif echo $line|grep -Pq "^[a-z]+=[0-9]{4}";then
			server[$index]=$rserver:`echo $line|awk -F= '{print $1"-"$2}'`
			((index++))
		fi
	done < $gamelist
	return 1
fi
#config
config=$dirconf/${id}.gconf
server=($address:$id-$port)
return 0
}

server=()
check_id
mode=$?
if [ $mode -eq 0 ];then
	check_address
	check_port
fi
l1='\n\t'
l2='\n\t\t'
l3='\n\t\t\t'
for i in ${server[@]};do
	address="${i%:*}"
	id=`echo $i|grep -Po "(?<=:)[a-z]+(?=-)"`
	config="$dirconf/${id}.gconf"
	echo -n "" > $config
	port="${i#*-}"
	echo "virtual_server_group $id {" >> $config
	for p in ${Address[@]};do
		for k in `seq 0 $((count-1))`;do
			echo -e "\t${p} $((port+k))" 
		done
	done >> $config
	echo "}" >> $config
	echo -e "virtual_server group $id {${l1}lb_algo rr${l1}lb_kind DR${l1}protocol TCP" >> $config
	echo -e "\treal_server $address {${l2}weight 1${l2}TCP_CHECK {${l3}connect_port ${port}${l3}connect_timeout 3${l3}nb_get_retry 3${l3}delay_before_retry 3${l2}}${l1}}" >> $config
	#echo -e "\treal_server $address {${l2}weight 1${l2}TCP_CHECK {${l3}connect_timeout 3${l3}nb_get_retry 3${l3}delay_before_retry 3${l3}connect_port ${port}${l2}}${l1}}" >> $config
	echo "}" >> $config
	echo -e "$config\t$address\t$id\t$port"
done
